package com.canis.stockmanager.web;

import com.canis.stockmanager.comm.Const;
import com.canis.stockmanager.comm.aop.LoggerManage;
import com.canis.stockmanager.domai.SysUser;
import com.canis.stockmanager.domai.result.ExceptionMsg;
import com.canis.stockmanager.domai.result.ResponseData;
import com.canis.stockmanager.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserRepository userRepository;
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseData login(SysUser user, HttpServletResponse response) {
        try {
            SysUser loginUser = userRepository.findByName(user.getName());
            if(loginUser==null){
                return new ResponseData(ExceptionMsg.LoginNameNotExists);
            }else if(!loginUser.getPassword().equals(getPwd(user.getPassword()))){
                return new ResponseData(ExceptionMsg.LoginNameOrPassWordError);
            }
            Cookie cookie = new Cookie(Const.LOGIN_SESSION_KEY, cookieSign(loginUser.getId().toString()));
            cookie.setMaxAge(Const.COOKIE_TIMEOUT);
            cookie.setPath("/");
            response.addCookie(cookie);
            getSession().setAttribute(Const.LOGIN_SESSION_KEY, loginUser);
            String preUrl = "/";
            return new ResponseData(ExceptionMsg.SUCCESS, preUrl);
        } catch (Exception e) {
            // TODO: handle exception
            logger.error("login failed, ", e);
            return new ResponseData(ExceptionMsg.FAILED);
        }
    }
}
